import { _decorator, Button, EditBox, find, Label, Sprite, Widget } from 'cc';
import { BasePopUp } from '../../../frame/component/ui.pop-up';
import type { ServiceAPIURI, ServiceBody } from '../../api/api.config.service';
import Config from '../../manager/config.manager';
import GameAssets from '../../manager/game.assets';
import { Float } from '../page/float';
import type { Popup } from '../page/popup';
const { ccclass, property } = _decorator;

type INFO = mtec.OmitO<ServiceBody<ServiceAPIURI.Free>, 'userId'|'freeID'>;

@ccclass('FreeInfo')
export class FreeInfo extends BasePopUp<typeof Popup, INFO> {
	protected default_return: INFO;

	private edit_name: EditBox;
	private edit_account: EditBox;
	private select_item: Button;
	private select_list: Array<Button>;
	private lbl_select: Label;

	protected initAfterOnLoad(): void {
		this.lbl_select = this.node.getChildByName('lbl-select').getComponent(Label);
		this.edit_name = this.node.getChildByName('edit-name').getComponent(EditBox);
		this.edit_account = this.node.getChildByName('edit-account').getComponent(EditBox);
		this.select_list = this.node.getChildByName('channel-container').getComponentsInChildren(Button);
		this.renderLocalUI();

		let focus_handle = mtec.cc.creatEventHandle({
			target: this.node,
			component: this.comp_name,
			handler: 'onFocus',
		});

		[this.edit_name, this.edit_account].forEach(ed=>ed.editingDidBegan.push(focus_handle));
	}

	public onShow(){
		this.selectChannel(this.select_list[0]);
		this.edit_name.string = '';
		this.edit_account.string = '';

		BasePopUp.jelly_enter(this.node);
	}

	protected ClickBtn(btn: Button): void {
		if(btn.node.name.startsWith('channel')){
			this.selectChannel(btn);
		}
	}

	protected _click_event_: { [name: string]: (this: FreeInfo, button: Button) => void; } = {
		async close(btn){
			btn.interactable = false;
			await BasePopUp.jelly_leave(this.node)
			this.close(null);
			btn.interactable = true;
		},
		async confirm(btn){
			btn.interactable = false;
			let verify = this.verifyInfo();
			if(verify.pass){
				let confirm = await this.pop.FreeConfirm(verify.info);
				if(confirm){
					await BasePopUp.jelly_leave(this.node);
					this.close(verify.info);
				}
			}
			btn.interactable = true;
		}
	};

	private selectChannel(button: Button){
		if(button == this.select_item){
			return void 0;
		}else if(this.select_item){
			this.enableChannel(this.select_item, true);
			this.enableChannel(button, false);
			this.select_item = button;
		}else{
			this.select_list.forEach(btn=>{
				this.enableChannel(btn, btn!=button);
				if(!btn.interactable){
					this.select_item = btn;
				}
			});
		}

		this.lbl_select.string = find('mask/channel', button.node).getComponent(Sprite).spriteFrame.name;
	}

	private enableChannel(btn: Button, enable: boolean){
		btn.interactable = enable;
		btn.node.getChildByName('bg-normal').active = enable;
		btn.node.getChildByName('bg-check').active = !enable;
		btn.node.getChildByName('icon-check').active = !enable;
	}

	private renderLocalUI(){
		let channel_list = Config.countryConf.channel;
		this.select_list.forEach((btn, idx)=>{
			btn.node.active = idx < channel_list.length;
			if(btn.node.active){
				btn.node.name = 'channel-'+channel_list[idx];
				mtec.cc.skinPeeler(find('mask/channel', btn.node), this.smap.get(channel_list[idx]), true);
			}
		});

		(<const>[
			['head', GameAssets.getLangText(69)],
			['desc', GameAssets.getLangText(70)],
			['confirm', GameAssets.getLangText(74)],
		]).forEach(([name, text])=>{
			this.node.getChildByName('lbl-'+name).getComponent(Label).string = text;
		});

		this.edit_name.placeholder = GameAssets.getLangText(72);
		this.edit_account.placeholder = GameAssets.getLangText(73);
	}

	private getInfo(): INFO{
		return {
			account: this.edit_account.string,
			accountName: this.edit_name.string,
			channel: this.select_item.node.name.split('-')[1],
			accountType: '',
		}
	}

	/** 验证收款信息 */
	private verifyInfo(){
		let pass = true;
		let info = this.getInfo();
		if(info.accountName.length <= 0){
			pass = false;
			Float.Hint(GameAssets.getLangText(79));
		}else if(info.account.length <= 0){
			pass = false
			Float.Hint(GameAssets.getLangText(80));
		}else{
			const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
			if(emailRegex.test(info.account)){
				info.accountType = 'EMAIL';
			}else{
				pass = false;
				Float.Hint(GameAssets.getLangText(81));
			}
		}
		return {pass, info};
	}

	private onFocus(ebox: EditBox){
		this.fixEditBox(ebox);
	}

	private fixEditBox(editbox: EditBox){
		[editbox.textLabel, editbox.placeholderLabel].forEach(lbl=>{
			let wgt = lbl.getComponent(Widget);
			if(!wgt){
				wgt = lbl.addComponent(Widget);
				[wgt.isAlignTop, wgt.isAlignBottom, wgt.isAlignLeft, wgt.isAlignRight] = [true, true, true, true];
				[wgt.isAbsoluteTop, wgt.isAbsoluteBottom, wgt.isAbsoluteLeft, wgt.isAbsoluteRight] = [true, true, true, true];
				[wgt.top, wgt.bottom, wgt.left, wgt.right] = [0, 0, 0, 0];
			}

			wgt.enabled = true;
			wgt.updateAlignment();
		});
	}
}

